package singleton.v1;

import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.checkerframework.checker.units.qual.s;

import com.mysql.jdbc.Connection;

/**
 * 枚举实现单例
 * @Description:
 * @author wanglong
 * @createDate: 2019年3月25日 下午9:35:57
 */
public class SingletonSafe5 {
	
	static {
		System.out.println("SingletonSafe5的静态代码块");
	}
	private SingletonSafe5() {
		System.out.println("SingletonSafe5的构造函数");
	}
	
	public enum SingletonSafe5Enum{
		connectionFactory;
		static {
			System.out.println("枚举类的静态代码块");
		}
		
		private Connection connection;
		
		private SingletonSafe5Enum() {
			System.out.println("枚举类的构造函数");
			Properties dbProperties = new Properties();
			InputStream is = SingletonSafe5.class.getClassLoader().getResourceAsStream("db.properties"); 
			try {
				dbProperties.load(is);
				connection = (Connection) DriverManager.getConnection(dbProperties.getProperty("url"), 
						dbProperties.getProperty("username"), dbProperties.getProperty("password"));
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				try {
					if(is != null)
						is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		public Connection getInstance() {
			return connection;
		}
	}
	
	public static void main(String[] args) {
		
		for(int i = 0; i < 5; i++) {
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					System.out.println(SingletonSafe5Enum.connectionFactory.getInstance());
				}
			}).start();
		}
		
	}

}
